<?php

require_once("page.class.php");
require_once("adrese.class.php");

class predracun extends page{
	
	public $db;
	public $adr;
	
	public $predracuni_archive = "predracuni";
	
	function predracun(){
		$this->db = new db_functions();
		$this->adr = new adrese();
		
		$a = getFromInput("a");
		switch ($a){
			default:
				$this->startForm();
				break;
			case "search":
				$this->searchUgovor();
				break;
			case "make":
				$this->make();
				break;
			case "save":
				$this->save();
				break;
			case "cenovnik":
				$dan=getFromInput("dan");
				$mes=getFromInput("mes");
				$god=getFromInput("god");
				$time = date2int("$dan.$mes.$god");
				echo page::getCenovnik($time);
				break;
		}
	}
	
	function startForm(){
		echo $this->parseTemplate("predracuni/search.tpl");
	}
	
	function make(){
		$ugoid = getFromInput("id"); $ugoid = (int)$ugoid;
		$obnova = getFromInput("obnova"); $obnova = $obnova=="on"?true:false;
		
		$ugovor = $this->db->getRow("SELECT * FROM ugovori WHERE id=$ugoid",true);
		//print_rarray($ugovor);
		if ($ugovor) {
			$this->assign("cenovnik",page::getCenovnik(time()));
			
			$porez_perc = $this->db->getOne("SELECT porez_percent FROM porezi WHERE porez_id=".$ugovor["porez"]." LIMIT 1");
			$this->assign("porez_perc",$porez_perc);
			
			$komitent = $this->db->getRow("SELECT * FROM komitenti WHERE komitent_id=".$ugovor["komitent"],true);
			$komitent_name = $komitent["komitent_name"];
			
			$this->assign("ugoid",$ugovor["broj"]);
			$this->assign("ugo_id",$ugovor["id"]);
			$this->assign("komitent_ime",$komitent_name);
			
			$komitent_adresa = $komitent["komitent_adresa"];
			$a = $this->adr->getAll($komitent_adresa);
			$this->assign("komitent_adresa",$a["ulica"]." ".$a["broj"]);
			$mesto = $a["lokacija"]["mesto"]["name"];
			$ptt = $a["lokacija"]["mesto"]["ptt"];
			if (isset($a["lokacija"]["opstina"]) && strlen($a["lokacija"]["opstina"]["ptt"])>0) {
				$ptt = $a["lokacija"]["opstina"]["ptt"];
			}
			if (isset($a["lokacija"]["naselje"]) && strlen($a["lokacija"]["naselje"]["ptt"])>0) {
				$ptt = $a["lokacija"]["naselje"]["ptt"];
			}
			$this->assign("komitent_mesto","$ptt $mesto");
			
			$this->assign("komitent_pib",$komitent["komitent_pib"]);
			$this->assign("komitent_tel",$this->db->getOne("SELECT telefon FROM komitenti_telefoni WHERE fax=0 AND del_id=0 AND kom_id=".$ugovor["komitent"]." ORDER BY `order` LIMIT 1"));
			$this->assign("komitent_fax",$this->db->getOne("SELECT telefon FROM komitenti_telefoni WHERE fax=1 AND del_id=0 AND kom_id=".$ugovor["komitent"]." ORDER BY `order` LIMIT 1"));
			$this->assign("komitent_email",$this->db->getOne("SELECT email FROM komitenti_emails WHERE del_id=0 AND kom_id=".$ugovor["komitent"]." LIMIT 1"));
			$this->assign("komitent_zr",$ugovor["komitent_ziro"]);

			//$this->assign("date",datetime2str($ugovor["datum"]));
			$this->assign("date",date("d.m.Y"));
			$stavke = $this->db->select2("SELECT * FROM ugovori_stavke WHERE iznos_bruto>0 AND ugovor_id=".$ugovor["id"]." ORDER BY iznos_bruto DESC");
			if ($stavke !== false) {
				$sumneto = $sumpopust = $sumporez = $sumbruto = 0;
				foreach ($stavke as $k=>$stavka){
					$count[] = $k;
					
					if ($stavka["paket"]>0) {
						$artikl = $this->get_CenePaket($stavka["artikl"]);
						$artpaketname = $artikl["name"]."<span class=\"paketinfo\">";
						foreach ($artikl["artikli"] as $a){
							$artpaketname .= "<br />&nbsp;&nbsp;&nbsp;&nbsp;- ".$a["name"]." (-".number_format($a["popust"],2,",",".").")";
						}
						$artpaketname .= "</span>";
						$artname[] = $artpaketname;
					}else{
						$artikl = $this->get_CeneArtikl($stavka["artikl"]);
						$full  = $artikl["art_full_name"];
						if (isset($full["mera"])) {
							unset($full["mera"]);
						}
						$artname[] = implode(" / ",$full);
					}
					
					$artneto_price = $artikl["price"];
					$artkol[] = $stavka["kolicina"];
					//$artneto[] = number_format($stavka["iznos_neto"],2,",",".");
					$artneto[] = number_format($artneto_price*$stavka["kolicina"],2,",",".");
					
					//$jed_cena = $stavka["kolicina"]>0?($stavka["iznos_neto"]/$stavka["kolicina"]):$stavka["kolicina"];
					$jed_cena = $artneto_price;
					$artneto_jed[] = number_format($jed_cena,2,",",".");
					$artpopustval= number_format($stavka["popust"],2,",",".");
					$artpopust[] = $artpopustval;
					if ($artneto_price>0)
						$artpopustperc[] =number_format($stavka["popust"] / $artneto_price*100,0);
					else $artpopustperc[] = 0;
					$artporez[] = number_format($stavka["porez"],2,",",".");
					$artbruto[] = number_format($stavka["iznos_bruto"],2,",",".");
					
					$sumneto	+= $stavka["iznos_neto"];
					$sumpopust	+= $stavka["popust"];
					$sumporez	+= $stavka["porez"];
					$sumbruto	+= $stavka["iznos_bruto"];
				}
				
				$osnovica_pdv = $sumneto-$sumpopust;
				$this->assign("osnovica_pdv",number_format($osnovica_pdv,2,",","."));
				
				$plan = $this->db->getRow("SELECT * FROM ugovori_plan_otplate WHERE ugovor_id=".$ugovor["id"]." LIMIT 1",true);
				
				$otplaceno = (float) $this->db->getOne("SELECT SUM(iznos) FROM ugovori_otplate WHERE ugoid=".$ugovor["id"]);
				$dug = $ugovor["iznos_bruto"]-$otplaceno;
				$this->assign("otplaceno",number_format($otplaceno,2,",","."));
				$this->assign("dugovanje",number_format($dug,2,",","."));
				
				
				$now = time();
				$sql = "SELECT bruto, datum "
					  ."FROM ugovori_plan_rate "
					  ."WHERE rata_plan=".$plan["plan_id"]." "
					  ."AND datum<=$now";
				$rate = $this->db->select2($sql);
				
				$plan_avans_time = date2int(datetime2str($plan["avans_date"]));
				if (($plan_avans_time<$now) && ((float) $otplaceno < (float) $ugovor["iznos_bruto"])) {
					$otplaceno -= $plan["avans_bruto"];
					if ($rate !== false){
						if ($otplaceno<0) {
							$zauplatu = abs($otplaceno)+$rate[0]["bruto"];
						}else{
							$zauplatu = 0;
							foreach ($rate as $rata){
								$tst = $otplaceno-$rata["bruto"];
								if ($tst<0) {
									$zauplatu = abs($tst);
								}
								$otplaceno -= $rata["bruto"];
							}
							if($zauplatu<$rate[count($rate)-1]["bruto"]){
								$zauplatu += $rate[count($rate)-1]["bruto"];
							}
						}
					}else{
						$zauplatu = $dug;
					}
				}else{
					$zauplatu = 0;
				}
				
				$vrrate = 0;
				if ($rate !== false) {
					$vrrate = $rate[0]["bruto"];
				}
				
				$this->assign("vrrate",number_format($vrrate,2,",","."));
				
				$nacin_placanja = $this->db->getOne("SELECT np_name FROM nacini_placanja WHERE np_id=".$plan["nacin_placanja"]." LIMIT 1");
				if ($plan["avans_bruto"]>0) {
					$avans_perc = round(100*$plan["avans_bruto"]/$ugovor["iznos_bruto"],2); 
					$placanje_avans = "$avans_perc%";
				}
				$broj_rata = $this->db->getOne("SELECT COUNT(rata_id) FROM ugovori_plan_rate WHERE rata_plan=".$plan["plan_id"]);
				$broj_rata = $broj_rata>0?(int) $broj_rata:0;
				if ($broj_rata>0) {
					$placanje_rate = $broj_rata;
					/*switch ($broj_rata){
						default:
						case 1:
							$placanje_rate .= " rata";
							break;
						case 2:
						case 3:
						case 4:
							$placanje_rate .= " rate";
							break;
					}*/
				}
				else $placanje_rate=0;
				
				$this->assign("tip_placanja",$nacin_placanja);
				$this->assign("placanje_avans",$placanje_avans);
				$this->assign("placanje_rate",$placanje_rate);
				
				$this->assign("zauplatu",number_format($zauplatu,2,",","."));
				$this->assign("avans",number_format($plan["avans_bruto"],2,",","."));
				
				$this->assign("count",$count);
				$this->assign("artname",$artname);
				$this->assign("artkol",$artkol);
				$this->assign("artneto",$artneto);
				$this->assign("artneto_jed",$artneto_jed);
				$this->assign("artpopust",$artpopust);
				$this->assign("artpopustperc",$artpopustperc);
				$this->assign("artporez",$artporez);
				$this->assign("artbruto",$artbruto);
				
				$this->assign("sumneto",number_format($sumneto,2,",","."));
				$this->assign("sumpopust",number_format($sumpopust,2,",","."));
				$this->assign("sumporez",number_format($sumporez,2,",","."));
				$this->assign("sumbruto",number_format($sumbruto,2,",","."));
			}
			
			if (!$obnova) {
				$this->assign("obnova_comment_start","<!--");
				$this->assign("obnova_comment_end","-->");
			}
			
			echo $this->parseTemplate("predracuni/predracun.tpl");
		}else{
			die("Ne postoji ugovor id=$ugovor");
		}
	}
	
	function save(){
		$code = 0;
		$content = readValFromInput("content");
		$ugovor = readValFromInput("ugovor");
		$ugovor_id = readValFromInput("ugoid");
		$datum_placanja=readValFromInput("datumplacanja");
		$datum_placanja=date2int($datum_placanja);

		$this->assign("ugoid","$ugovor, ".date("d.m.Y"));
		$this->assign("predracun",$content);
		$content = $this->parseTemplate("predracuni/save_template.tpl");
		
		$filename = $this->predracuni_archive."/PR_".preg_replace('/[\/]/','_',$ugovor)."_".date("Y-m-d").".html";
		if(!file_put_contents($filename,$content)){
			$code = 1;
			$msg = "Save failed!";
		}
		else {
			$q="insert into predracuni(ugovor_id,datum_slanja,datum_placanja)";
			$q.="values(".$ugovor_id.",".time().",".$datum_placanja.")";
			echo $q;
			$res=$this->db->alterTable($q);
			if (!$res)
			{
				$code=2;
				$msg = "Save in database failed!";
			}
		}
		echo "$code{!}$msg";
	}
		
	function searchUgovor(){
		$k = getFromInput("filter_ugovor");
		$obnova = getFromInput("obnova");
		
		$sk = prepForSQL($k);
		$q = "SELECT id, broj, datum, komitent, komitent_name, iznos_bruto, tip_ugovora "
			."FROM ugovori, komitenti "
			."WHERE komitenti.komitent_id=ugovori.komitent AND ("
			."ugovori.id='$k' "
			."OR broj LIKE '%$sk%' "
			."OR komitent='$k' "
			."OR komitent_name LIKE '%$sk%' "
			."OR komitent_ziro LIKE '%$sk%') "
			."LIMIT 0,50";
		$res = $this->db->select2($q);
		
		if ($res !== false) {
			$num = count($res);
			foreach ($res as $k=>$v){
				$item = "";
				$nums[] = $v["broj"];
				
				$otplaceno = (float) $this->db->getOne("SELECT SUM(iznos) FROM ugovori_otplate WHERE ugoid=".$v["id"]);
				$dug = (float)$v["iznos_bruto"]-$otplaceno;
				$item .= '<span class="price">'.number_format($v["iznos_bruto"],2,",",".").'</span>';
				if ($dug>0) {
					$item .= '<span class="dug">'.number_format($dug,2,",",".").'</span> ';
				}
				$item .= $v["komitent"].". ".$v["komitent_name"];
				
				$click = "closeYpAjaxForm();";
				$click .= "LoadRSDoc('predracun.php?a=make&id=".$v["id"]."&obnova=$obnova','afterSearchPredracun');";
				
				$clicks[] = $click;
				$items[] = $item;
			}
			$this->assign("list_num",$nums);
			$this->assign("list_item",$items);
			$this->assign("onclick",$clicks);
		}else{
			$num = 0;
		}
		
		$this->assign("search_length",$num);
		
		echo $this->parseTemplate("search_list.tpl");
	}
}

?>